﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Puerts;

public class TypeScriptCreator
{
    [MenuItem("Assets/Create/Type Script", false, 80)]
    public static void CreateNewPythonScript()
    {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, 
            ScriptableObject.CreateInstance<DoCreatePythonScript>(),
            GetSelectedPathOrFallback() + "/NewTypeScript.ts", 
            ThambNail(),
            // AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/unity-python/Gizmos/PythonScript Icon.png"),
            string.Empty);
    }

    public static string GetSelectedPathOrFallback()
    {
        string path = "Assets";
        foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
        {
            path = AssetDatabase.GetAssetPath(obj);
            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                path = Path.GetDirectoryName(path);
                break;
            }
        }
        return path;
    }

    public static Texture2D ThambNail()
    {
        string s = JsLoader.Puerts_Extens.Substring(JsLoader.Puerts_Extens.IndexOf("Assets"));
        s = Path.Combine(s,"Editor/icon");
        Texture2D t = AssetDatabase.LoadAssetAtPath(s + ".png", typeof(Texture2D)) as Texture2D;
        if (t)
            return t;
        return  AssetDatabase.LoadAssetAtPath(s + ".jpg", typeof(Texture2D)) as Texture2D;
    }

    class DoCreatePythonScript : EndNameEditAction
    {
        static string TemplateText = @"//逻辑代码
import {Puerts, UnityEngine} from 'csharp'
import {$typeof} from 'puerts'
import {Component} from 'framework/component/component';

class #NAME#  extends Component
{
    //private behaviour : JsBehaviour;
    constructor(behaviour:Puerts.JsBehaviour) {
        super(behaviour);
        //继承component不需要自己手动添加钩子赋值,删掉就行. 不然按具体需求打开注释,重写具体方法
        //behaviour._jsAwake = ()=>this.Awake();
        //behaviour._jsStart = ()=> this.Start();
        //behaviour._jsOnDisable = ()=> this.OnDisable();
        //behaviour._jsOnEnable = ()=> this.OnEnable();
        //behaviour._jsOnDestroy = ()=> this.OnDestroy();
    }
    //Awake(){
    //  console.log('js Awake ...')
    // }
    // Start (){
    //     console.log('js Start ...')
    // }
    //OnEnable(){
    //      console.log('js OnEnable ...')
    // }
    //OnDisable(){
    //      console.log('js OnDisable ...')
    // }
    // LateUpdate(){//注册到componentmgr的事件        
    // }
    //FixedUpdate(){//注册到componentmgr的事件
    //}
    // Update() //注册到componentmgr的事件
    // {
    //     //js不支持操作符重载所以Vector3的乘这么用
    //     let r = UnityEngine.Vector3.op_Multiply(UnityEngine.Vector3.up, UnityEngine.Time.deltaTime * 10);
    //     this.behavior.transform.Rotate(r);
    // }
    // public OnDestroy() {
    //     super.OnDestroy()
    //     console.log('Mainmenu OnDestroy...');
    // }
}

export function init (jsBehavior:Puerts.JsBehaviour) {
    new #NAME#(jsBehavior);
}
";

        public override void Action(int instanceId, string pathName, string resourceFile)
        {
            UnityEngine.Object o = CreateScriptAssetFromTemplate(pathName, resourceFile);
            ProjectWindowUtil.ShowCreatedAsset(o);
        }

        internal static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
        {
            string fullPath = Path.GetFullPath(pathName);
            string text = TemplateText;
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
            text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension);
            bool encoderShouldEmitUTF8Identifier = true;
            bool throwOnInvalidBytes = false;
            UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
            bool append = false;
            StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
            streamWriter.Write(text);
            streamWriter.Close();
            AssetDatabase.ImportAsset(pathName);
            return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
        }
    }
}